<template>
  <a-modal
    :title="formTile + '元素'"
    :visible="true"
    width="60%"
    :footer="null"
    @cancel="reset"
  >
    <a-card>
      <a-row
        type="flex"
        justify="start"
        align="top"
      >
        <a-col :span="24">
          <a-form
            :form="form"
            @submit="handleSubmit"
            :labelCol="formItemLayout.labelCol"
            :wrapperCol="formItemLayout.wrapperCol"
          >
            <a-form-item
              label="名称"
              :required="true"
            >
              <a-input
                allow-clear
                placeholder="请输入名称"
                :maxLength="40"
                v-decorator="[
                  `name`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入名称'
                      }
                    ]
                  }
                ]"
              />
            </a-form-item>
             <a-form-item
              label="品牌"
              :required="true"
            >
              <a-select
                allow-clear
                show-search
                placeholder="请选择品牌"
                optionFilterProp="children"
                @change="selectChange"
                @search="searchBrand"
                v-decorator="[
                  'brand',
                  {
                    rules: [{ required: true, message: '请选择品牌!' }]
                  }
                ]"
              >
                <a-spin
                  v-if="branding"
                  slot="notFoundContent"
                  size="small"
                />
                <a-select-option
                  :value="item.code"
                  v-for="item in brandList"
                  :key="item.code"
                >
                  {{ item.value }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              label="分类"
              :required="true"
            >
              <a-select
                allow-clear
                show-search
                placeholder="请选择分类"
                optionFilterProp="children"
                @search="handleSearch"
                v-decorator="[
                  'categoryId',
                  {
                    rules: [{ required: true, message: '请选择分类!' }]
                  }
                ]"
              >
                <a-spin
                  v-if="fetching"
                  slot="notFoundContent"
                  size="small"
                />
                <a-select-option
                  :value="item.id"
                  v-for="item in categories"
                  :key="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              label="描述"
              :required="true"
            >
               <a-textarea allow-clear placeholder="请输入描述"  :maxLength="150"  v-decorator="[
                  `description`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入描述'
                      }
                    ]
                  }
                ]"></a-textarea>
            </a-form-item>
             <a-form-item label="是否存在敏感风险">
              <a-switch
                v-decorator="[
                  'riskFlag',
                  { initialValue: false, valuePropName: 'checked', rules: [{ required: true, message: '请选择是否存在敏感风险！' }] },
                ]"
                @change="changeRisk"
              ></a-switch>
            </a-form-item>
            <a-form-item v-if="showRisk" label="敏感风险">
              <a-checkbox-group v-decorator="['risk', {rules: [{ required: true, message: '请选择存在的敏感风险！' }]}]">
                <a-row>
                  <a-col
                    :span="16"
                    v-for="(item,index) in riskList"
                    :key="index"
                  >
                    <a-checkbox :value="item.value">
                      {{ item.title }}
                      <a-popover>
                        <template slot="content">
                          <p v-for="(tip,index) in item.tips" :key="index">
                             {{tip}}
                          </p>
                         
                        </template>
                        <a-icon
                          type="question-circle"
                          theme="twoTone"
                          class="tips"
                        />
                      </a-popover>
                    </a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
            </a-form-item>
            <a-form-item
              label="图片"
              :required="true"
            >
              <a-upload
                name="file"
                list-type="picture-card"
                class="avatar-uploader"
                :data="{ type: 1 }"
                :show-upload-list="false"
                :action="uploadUrl"
                :before-upload="beforeUpload"
                @change="handleChange"
                v-decorator="[
                  'url',
                  {
                    valuePropName: 'fileList',
                    getValueFromEvent: normFile,
                    validateTrigger: ['blur'],
                    rules: [{ required: true, message: '请上传图片' }]
                  }
                ]"
              >
                <img
                  v-if="imageUrl"
                  style="width:110px;height:auto"
                  :src="imageUrl"
                  alt="avatar"
                />
                <div v-else>
                  <a-icon :type="uploading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-item>

            <a-row>
              <a-col
                :span="16"
                :offset="8"
                class="info-action"
              >
                <a-button
                  type="primary"
                  @click="reset"
                >返回</a-button>
                <a-button
                  type="primary"
                  class="ml-20"
                  html-type="submit"
                  :loading="loading"
                >保存</a-button>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
    </a-card>
  </a-modal>
</template>

<script>
import aliossImageUpload from '@/components/aliossImageUpload'
import debounce from 'lodash/debounce'
import { getSystemPro,categoryList, currencyCreate, currencyUpdate, uploadUrl ,queryDetail,queryFull} from '@api/pattern/index.js'
const riskList = [
  {
    title: '原创／著作问题',
    value:"10",
    tips: ['1.包含其他作品(艺术品/画作等)或者其他品牌logo。例如：未经授权不可包含第三方作品及其他品牌logo','2.包含一些个人隐私信息。例如：素材中不能包含个人信息、名字、手机、身份证、车牌等','3.没有肖像授权。例如：素材中的模特需提前签订肖像授权','4.包含一些无法提供证明的用词?“最”"第一等。例如：素材中不能出现无法提供报告证明的文字描述，违反广告法'],
  },
  {
    title: '社会和谐',
    value:"20",
    tips: ['1.有恐怖、暴力倾向。例如：枪支，而腥、斗殴，愤怒等，暴力也包含冷暴力','2.有色情或性暗示倾向。例如：过度裸震姿势暗示性元素及语言等','3.有邪教图案。例如：佛像、撒旦元素、耶稣十字架、法轮功等','4.有恋童倾向。例如：儿童做一些性暗示的动作，或者和此类元素互动'],
  },
  {
    title: '政治敏感',
    value:"30",
    tips: ['1.包含了错误的地图及地域信息。例如：台湾问题及地图不完整，涉及国家主权问题','2.提及人物是否有反华的言论。例如：D&G创始人在facebook的言论','3.有辱华的元素。例如：东方人丑化=眯眯眼，三只松鼠海报事件','4.包含一些历史事件元素。例如：历史革命的元素和标志，“平等”“主席像”“坦克”等','5.发布时间，是否恰当。例如：918事变，77卢沟桥事变，1213南京大屠杀。512汶川地震等','6.包含其他国家的国旗、军旗、侵略国的元素。例如：穿国旗事件，靖国神社前拍照'],
  },
  {
    title: '文化歧视',
    value:"40",
    tips: ['1.影射种族歧视。例如：有色人群:黑人=猩猩，辱华:中国人=眯眯眼','2.对女性的物化及不尊重。例如：存在对物化、过度定义不尊重','3.少于50%是中国亚洲模特。例如：中国设计师品牌的立场','4.对特殊人群的暗讽。例如：佛像，撒日元素，耶稣十字架，法轮功等'],
  },
  {
    title: '语言问题',
    value:"50",
    tips: ['1.英文含义解读是否有风险。例如：welcometo hell，不能当作图案使用','2.英文表示在西方文化中是否有双关含义。例如：Dog 直译是狗，但会有侮辱嫌疑，可以改用puppy'],
  },
  {
    title: '未成年人风险',
    value:"60",
    tips: ['1.是否含有引发未成年人模仿违反社会公德的行为和违法犯罪的行为。','2.是否含有恐怖、残酷等可能妨害未成年人身心健康的行为。','3.是否含有可能引发未成年人模仿的不安全行为。','4.是否可能引发未成年人产生不良情绪、养成不良嗜好。','5.如素材涉及境外文化作品的，是否来源于国内审定引进版本'],
  },
]
export default {
  props: {
    element: {
      type: Object,
      default: null
    }
  },

  data() {
    this.handleSearch = debounce(this.handleSearch, 800)
    this.searchBrand = debounce(this.searchBrand, 800)
    return {
      current: 1,
      size: 1000,
      total: 0,
      riskList,
      showRisk: false,
      loading: false,
      fileds: [],
      uploading: false,
      templates: [],
      formItemLayout: {
        labelCol: {
          xl: { span: 5 },
          xs: { span: 5 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xl: { span: 8 },
          xs: { span: 12 },
          sm: { span: 12 }
        }
      },
      fileList: [],
      imageUrl: '',
      categoryName:'',
      loading: false,
      record: null,
      pushType: undefined,
      formTile: '新增',
      brandChange:false,
      categories: [],
      brandList:[],
      fetching: false,
      branding:false,
      uploadUrl
    }
  },

  computed: {
    jobNumber() {
      return this.$store.getters.userInfo.workNo || ''
    }
  },

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'element' })
  },

  created() {
    this.handleSearch()
    this.searchBrand()
    const { element } = this.$props
    if (element) {
      this.formTile = '编辑'
      this.$nextTick(() => {
          this.getDetail( element.id)
     
      })
       
    }
  },

  methods: {
     async getDetail(id) {
     const res = await queryDetail('element', { id })
     if(res.data.brand){
       this.brandChange = res.data.brand
        this.handleSearch()
     }
     if (res.data.url && res.data.url !== '') {
       
          this.imageUrl = res.data.url
          this.form.setFieldsValue({
            url: [
              {
                name: res.data.url,
                uid: res.data.url,
                status: 'done',
                url: res.data.url,
               
              }
            ]
          })
        }
        this.form.setFieldsValue({
          categoryId: res.data.categoryId,
          description: res.data.description,
           brand:res.data.brand,
          name: res.data.name ,
          riskFlag : res.data.riskFlag == 1
        })
        if (res.data.riskFlag == 1) {
          this.showRisk = true
          this.$nextTick(() => {
            this.form.setFieldsValue({
              risk: res.data.risk,
            })
          })
        }
     },
    async getCategoryList(brand) {
      this.categories = []
      const { size, current } = this
      this.fetching = true
      const res = await categoryList({ size, current,brand,type:10 })
      this.fetching = false
      if (res.code == 200) {
        this.categories = res.data.records
      }
      
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.uploading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        this.imageUrl = info.file.response.data.url
        this.uploading = false
      }
      if (info.file.status === 'error') {
        this.$message.error('图片上传失败')
      }
    },
    normFile(e) {
      console.log('Upload event:', e)
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
    selectChange(brand){
      this.brandChange = brand
      this.handleSearch()
    },
    beforeUpload: function(file) {
      var fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请上传图片')
        return false
      }
    },
    async handleSearch(name) {
      this.fetching = true
      this.categories=[]
      const params = {
        jobNumber:this.jobNumber,
        elementFlag:0,
        type:10
      }
       if(this.brandChange){
        params.brand = this.brandChange
      }
      const res = await queryFull('category',params)
      this.fetching = false
      if (res.code == 200) {
        this.categories = res.data
      }
    },

     async searchBrand() {
      this.branding = true
      const data ={
        jobNumber : this.jobNumber
      }
      const res = await getSystemPro( 'brand',data)
      this.branding = false
      if (res.code == 200) {
        this.brandList = res.data
      }else{
        this.$message.error(res.msg || res.message)
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        // console.log(err, values)
        if (!err) {
          this.submit(values)
        }
      })
    },
      changeRisk(status) {
      this.showRisk = status
    },
    async submit(values) {
      this.loading = true
      const { element, jobNumber } = this
      if (element) {
        values.id = element.id
      }
      values.jobNumber = jobNumber
      values.riskFlag = values.riskFlag ? 1 : 0
      const index = values.url.length - 1
      values.url = values.url[index].response ? values.url[index].response.data.url : values.url[index].url
      const FNCName = element ? currencyUpdate : currencyCreate
      const res = await FNCName('element', values)
      if (res.code == 200) {
        let text = element ? '编辑成功' : '新增成功'
        this.$message.success(text)
        let operate = element ? 1 : 0
        this.categories.map((item)=>{
          
          if(item.id == values.categoryId){
             this.categoryName = item.name
            
          }
        })
        this.reset(values, operate,this.categoryName)
      } else {
        this.$message.error(res.msg || res.message)
          this.loading = false
      }
    },
    reset(values, operate,categoryName) {
      this.form.resetFields()
      this.loading = false
      this.fileList = []
      this.fileds = []
      this.$emit('close',values, operate,categoryName)
    }
  }
}
</script>

<style scoped lang="less">
.info-action {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-end;
  // margin-bottom: 20px;
}
.ml-20 {
  margin-left: 20px;
}
.poster {
  width: 100px;
  height: 100px;
  margin-right: 20px;
  position: relative;
  &:hover {
    .img-modal {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .img {
    width: 100%;
    height: 100%;
  }
  .img-modal {
    background-color: rgba(0, 0, 0, 0.5);
    display: none;
    position: absolute;
    color: #fff;
    font-size: 20px;
    width: 100%;
    top: 0;
    height: 100%;
    left: 0;
  }
}
.fileList {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
}
</style>